package com.andengine.editor.atlaseditor;

import com.gooddies.graphics.ExtRectangle;
import com.swingson.exceptions.ErrorMessageException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JToolTip;
import javax.swing.SwingUtilities;

/**
 * @author sad
 */
public class ImageTooltip extends JToolTip {

    private BufferedImage image;
    private ExtRectangle rect;

    public ImageTooltip(String filePath) {
        try {
            image = ImageIO.read(new File(filePath));
            rect = new ExtRectangle(0, 0, image.getWidth(), image.getHeight());
            rect.fitProportional(new Rectangle(80, 80));
        } catch (IOException ex) {
            throw new ErrorMessageException("Cannot load image " + filePath);
        }
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.BLACK);
        FontMetrics metrics = getFontMetrics(getFont());
        String dimensionString = "" + image.getWidth() + "x" + image.getHeight();
        int width = SwingUtilities.computeStringWidth(metrics, dimensionString);
        int height = metrics.getHeight();
        g.drawImage(image, (int) (getWidth() / 2 - rect.getWidth() / 2), 20, (int) rect.getWidth(), (int) rect.getHeight(), this);
        g.drawString(dimensionString, (int) (getWidth() / 2 - width / 2), height-2);
        g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(80, (int) (20 + rect.getHeight() + 1));
    }
}
